package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Map;

public class EchoHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);

        try {
            Map<String, String> allParams = request.getAllParams();
            Map<String, String> urlParams = request.getUrlParams();
            Map<String, String> bodyParams = request.getBodyParams();
            Map<String, String> headers = request.getHeaders();

            // 构建完整的HTML响应内容
            StringBuilder htmlBuilder = new StringBuilder();
            htmlBuilder.append("<!DOCTYPE html>\n")
                    .append("<html lang=\"zh-CN\">\n")
                    .append("<head>\n")
                    .append("    <meta charset=\"UTF-8\">\n")
                    .append("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n")
                    .append("    <title>Echo 服务 - MiniWebSvr</title>\n")
                    .append("    <style>\n")
                    .append("        body {\n")
                    .append("            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n")
                    .append("            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);\n")
                    .append("            margin: 0;\n")
                    .append("            padding: 20px;\n")
                    .append("            color: #333;\n")
                    .append("        }\n")
                    .append("        .container {\n")
                    .append("            max-width: 1000px;\n")
                    .append("            margin: 0 auto;\n")
                    .append("            background: white;\n")
                    .append("            border-radius: 15px;\n")
                    .append("            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);\n")
                    .append("            padding: 30px;\n")
                    .append("        }\n")
                    .append("        h1 {\n")
                    .append("            color: #d63031;\n")
                    .append("            text-align: center;\n")
                    .append("            margin-bottom: 30px;\n")
                    .append("            border-bottom: 2px solid #ffeaa7;\n")
                    .append("            padding-bottom: 10px;\n")
                    .append("        }\n")
                    .append("        .section {\n")
                    .append("            margin-bottom: 25px;\n")
                    .append("            padding: 20px;\n")
                    .append("            background: #f8f9fa;\n")
                    .append("            border-radius: 10px;\n")
                    .append("            border-left: 4px solid #74b9ff;\n")
                    .append("        }\n")
                    .append("        .section h2 {\n")
                    .append("            color: #2d3436;\n")
                    .append("            margin-top: 0;\n")
                    .append("        }\n")
                    .append("        table {\n")
                    .append("            width: 100%;\n")
                    .append("            border-collapse: collapse;\n")
                    .append("            margin: 15px 0;\n")
                    .append("        }\n")
                    .append("        th, td {\n")
                    .append("            padding: 12px 15px;\n")
                    .append("            text-align: left;\n")
                    .append("            border-bottom: 1px solid #ddd;\n")
                    .append("        }\n")
                    .append("        th {\n")
                    .append("            background-color: #74b9ff;\n")
                    .append("            color: white;\n")
                    .append("            font-weight: bold;\n")
                    .append("        }\n")
                    .append("        tr:hover {\n")
                    .append("            background-color: #f5f5f5;\n")
                    .append("        }\n")
                    .append("        .empty-message {\n")
                    .append("            text-align: center;\n")
                    .append("            color: #636e72;\n")
                    .append("            font-style: italic;\n")
                    .append("            padding: 20px;\n")
                    .append("        }\n")
                    .append("        .student-info {\n")
                    .append("            background: #ffeaa7;\n")
                    .append("            padding: 15px;\n")
                    .append("            border-radius: 8px;\n")
                    .append("            margin-top: 20px;\n")
                    .append("            text-align: center;\n")
                    .append("        }\n")
                    .append("        .method-badge {\n")
                    .append("            display: inline-block;\n")
                    .append("            padding: 5px 10px;\n")
                    .append("            background: #00b894;\n")
                    .append("            color: white;\n")
                    .append("            border-radius: 5px;\n")
                    .append("            font-weight: bold;\n")
                    .append("        }\n")
                    .append("        .post-badge {\n")
                    .append("            background: #e17055;\n")
                    .append("        }\n")
                    .append("        .test-form {\n")
                    .append("            background: #dfe6e9;\n")
                    .append("            padding: 20px;\n")
                    .append("            border-radius: 8px;\n")
                    .append("            margin: 20px 0;\n")
                    .append("        }\n")
                    .append("        .form-group {\n")
                    .append("            margin-bottom: 15px;\n")
                    .append("        }\n")
                    .append("        .form-group label {\n")
                    .append("            display: block;\n")
                    .append("            margin-bottom: 5px;\n")
                    .append("            font-weight: bold;\n")
                    .append("        }\n")
                    .append("        .form-group input {\n")
                    .append("            width: 100%;\n")
                    .append("            padding: 8px;\n")
                    .append("            border: 1px solid #ddd;\n")
                    .append("            border-radius: 4px;\n")
                    .append("        }\n")
                    .append("        .submit-btn {\n")
                    .append("            background: #00b894;\n")
                    .append("            color: white;\n")
                    .append("            border: none;\n")
                    .append("            padding: 10px 20px;\n")
                    .append("            border-radius: 4px;\n")
                    .append("            cursor: pointer;\n")
                    .append("            font-weight: bold;\n")
                    .append("        }\n")
                    .append("        .submit-btn:hover {\n")
                    .append("            background: #00a085;\n")
                    .append("        }\n")
                    .append("    </style>\n")
                    .append("</head>\n")
                    .append("<body>\n")
                    .append("    <div class=\"container\">\n")
                    .append("        <h1>🔄 Echo 服务器响应</h1>\n")
                    .append("        \n")
                    .append("        <div class=\"section\">\n")
                    .append("            <h2>请求基本信息</h2>\n")
                    .append("            <p><strong>请求方法:</strong> <span class=\"method-badge " +
                            ("POST".equals(request.getMethod()) ? "post-badge" : "") + "\">")
                    .append(request.getMethod()).append("</span></p>\n")
                    .append("            <p><strong>请求URL:</strong> ").append(request.getUrl()).append("</p>\n")
                    .append("        </div>\n");

            // 显示所有参数（合并URL和Body参数）
            htmlBuilder.append("        <div class=\"section\">\n")
                    .append("            <h2>所有参数（URL + Body）</h2>\n");

            if (allParams.isEmpty()) {
                htmlBuilder.append("            <div class=\"empty-message\">\n")
                        .append("                <p>📭 没有接收到任何参数</p>\n")
                        .append("            </div>\n");
            } else {
                htmlBuilder.append("            <table>\n")
                        .append("                <thead>\n")
                        .append("                    <tr>\n")
                        .append("                        <th>参数名</th>\n")
                        .append("                        <th>参数值</th>\n")
                        .append("                    </tr>\n")
                        .append("                </thead>\n")
                        .append("                <tbody>\n");

                for (Map.Entry<String, String> entry : allParams.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue() != null ? entry.getValue() : "(空值)";

                    htmlBuilder.append("                    <tr>\n")
                            .append("                        <td><strong>").append(escapeHtml(key)).append("</strong></td>\n")
                            .append("                        <td>").append(escapeHtml(value)).append("</td>\n")
                            .append("                    </tr>\n");
                }

                htmlBuilder.append("                </tbody>\n")
                        .append("            </table>\n")
                        .append("            <p><strong>总计:</strong> ").append(allParams.size()).append(" 个参数</p>\n");
            }

            htmlBuilder.append("        </div>\n");

            // 分别显示URL参数和POST参数
            htmlBuilder.append("        <div class=\"section\">\n")
                    .append("            <h2>URL 参数</h2>\n");

            if (urlParams.isEmpty()) {
                htmlBuilder.append("            <div class=\"empty-message\">\n")
                        .append("                <p>📭 没有URL参数</p>\n")
                        .append("            </div>\n");
            } else {
                htmlBuilder.append("            <table>\n")
                        .append("                <thead>\n")
                        .append("                    <tr>\n")
                        .append("                        <th>参数名</th>\n")
                        .append("                        <th>参数值</th>\n")
                        .append("                    </tr>\n")
                        .append("                </thead>\n")
                        .append("                <tbody>\n");

                for (Map.Entry<String, String> entry : urlParams.entrySet()) {
                    htmlBuilder.append("                    <tr>\n")
                            .append("                        <td><strong>").append(escapeHtml(entry.getKey())).append("</strong></td>\n")
                            .append("                        <td>").append(escapeHtml(entry.getValue())).append("</td>\n")
                            .append("                    </tr>\n");
                }

                htmlBuilder.append("                </tbody>\n")
                        .append("            </table>\n");
            }

            htmlBuilder.append("        </div>\n");

            // POST参数部分
            htmlBuilder.append("        <div class=\"section\">\n")
                    .append("            <h2>POST 参数</h2>\n");

            if (bodyParams.isEmpty()) {
                htmlBuilder.append("            <div class=\"empty-message\">\n")
                        .append("                <p>📭 没有POST参数</p>\n");

                // 如果不是POST请求，显示提示信息
                if (!"POST".equalsIgnoreCase(request.getMethod())) {
                    htmlBuilder.append("                <p>当前不是POST请求，使用以下工具测试POST请求：</p>\n");
                }
                htmlBuilder.append("            </div>\n");
            } else {
                htmlBuilder.append("            <table>\n")
                        .append("                <thead>\n")
                        .append("                    <tr>\n")
                        .append("                        <th>参数名</th>\n")
                        .append("                        <th>参数值</th>\n")
                        .append("                    </tr>\n")
                        .append("                </thead>\n")
                        .append("                <tbody>\n");

                for (Map.Entry<String, String> entry : bodyParams.entrySet()) {
                    htmlBuilder.append("                    <tr>\n")
                            .append("                        <td><strong>").append(escapeHtml(entry.getKey())).append("</strong></td>\n")
                            .append("                        <td>").append(escapeHtml(entry.getValue())).append("</td>\n")
                            .append("                    </tr>\n");
                }

                htmlBuilder.append("                </tbody>\n")
                        .append("            </table>\n");
            }

            htmlBuilder.append("        </div>\n");

            // 添加POST测试表单
            htmlBuilder.append("        <div class=\"section\">\n")
                    .append("            <h2>POST 请求测试</h2>\n")
                    .append("            <div class=\"test-form\">\n")
                    .append("                <form action=\"/echo\" method=\"post\">\n")
                    .append("                    <div class=\"form-group\">\n")
                    .append("                        <label for=\"name\">姓名:</label>\n")
                    .append("                        <input type=\"text\" id=\"name\" name=\"name\" value=\"李明燊\">\n")
                    .append("                    </div>\n")
                    .append("                    <div class=\"form-group\">\n")
                    .append("                        <label for=\"studentId\">学号:</label>\n")
                    .append("                        <input type=\"text\" id=\"studentId\" name=\"studentId\" value=\"222024321072047\">\n")
                    .append("                    </div>\n")
                    .append("                    <div class=\"form-group\">\n")
                    .append("                        <label for=\"course\">课程:</label>\n")
                    .append("                        <input type=\"text\" id=\"course\" name=\"course\" value=\"Java Web开发\">\n")
                    .append("                    </div>\n")
                    .append("                    <div class=\"form-group\">\n")
                    .append("                        <label for=\"message\">消息:</label>\n")
                    .append("                        <input type=\"text\" id=\"message\" name=\"message\" value=\"这是一个POST请求测试\">\n")
                    .append("                    </div>\n")
                    .append("                    <button type=\"submit\" class=\"submit-btn\">发送 POST 请求</button>\n")
                    .append("                </form>\n")
                    .append("            </div>\n")
                    .append("        </div>\n");

            // 添加请求头信息
            htmlBuilder.append("        <div class=\"section\">\n")
                    .append("            <h2>请求头信息</h2>\n");

            if (headers.isEmpty()) {
                htmlBuilder.append("            <div class=\"empty-message\">\n")
                        .append("                <p>📭 没有请求头信息</p>\n")
                        .append("            </div>\n");
            } else {
                htmlBuilder.append("            <table>\n")
                        .append("                <thead>\n")
                        .append("                    <tr>\n")
                        .append("                        <th>Header 名称</th>\n")
                        .append("                        <th>Header 值</th>\n")
                        .append("                    </tr>\n")
                        .append("                </thead>\n")
                        .append("                <tbody>\n");

                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    htmlBuilder.append("                    <tr>\n")
                            .append("                        <td><strong>").append(escapeHtml(entry.getKey())).append("</strong></td>\n")
                            .append("                        <td>").append(escapeHtml(entry.getValue())).append("</td>\n")
                            .append("                    </tr>\n");
                }

                htmlBuilder.append("                </tbody>\n")
                        .append("            </table>\n");
            }

            htmlBuilder.append("        </div>\n");

            // 添加开发者信息
            htmlBuilder.append("        <div class=\"student-info\">\n")
                    .append("            <h3>开发者信息</h3>\n")
                    .append("            <p><strong>学号:</strong> 222024321072047 | <strong>姓名:</strong> 李明燊</p>\n")
                    .append("            <p><strong>处理器:</strong> EchoHandler | <strong>服务器:</strong> MiniWebSvr</p>\n")
                    .append("        </div>\n")
                    .append("    </div>\n")
                    .append("</body>\n")
                    .append("</html>");

            String htmlContent = htmlBuilder.toString();

            // 构造完整的 HTTP 响应头
            writer.println("HTTP/1.1 200 OK");
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Content-Length: " + htmlContent.getBytes("UTF-8").length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println("Cache-Control: no-cache, no-store, must-revalidate");
            writer.println("Pragma: no-cache");
            writer.println("Expires: 0");
            writer.println(); // 空行分隔头部和主体

            writer.print(htmlContent);
            writer.flush();

            System.out.println("EchoHandler: 成功处理 " + request.getMethod() + " 请求");
            System.out.println("  - URL参数: " + urlParams.size() + " 个");
            System.out.println("  - POST参数: " + bodyParams.size() + " 个");
            System.out.println("  - 总计参数: " + allParams.size() + " 个");

        } catch (Exception e) {
            System.err.println("EchoHandler处理异常: " + e.getMessage());
            e.printStackTrace();

            // 发生异常时返回错误响应
            try {
                String errorResponse = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/plain; charset=UTF-8\r\n" +
                        "Connection: close\r\n" +
                        "\r\n" +
                        "Echo服务器在处理请求时发生错误";
                response.write(errorResponse.getBytes("UTF-8"));
            } catch (IOException ioException) {
                System.err.println("发送错误响应失败: " + ioException.getMessage());
            }
        }
    }

    /**
     * HTML转义，防止XSS攻击
     * @param text 原始文本
     * @return 转义后的文本
     */
    private String escapeHtml(String text) {
        if (text == null) {
            return "";
        }
        return text.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }
}